﻿using Castle.DynamicProxy;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace HBKY.Shop.Common.PollyHelper
{
    /// <summary>
    /// Api动态代理
    /// </summary>
    public class RequestApiProxy
    {
        /// <summary>
        /// Get
        /// </summary>
        public static async Task<T> Get<T>(HttpClient httpClient, string url, string parameter = null) where T : class, new()
        {
          return await SoftInvoke(async () => 
            {
                ProxyGenerator generator = new ProxyGenerator();
                CustomInterceptor interceptor = new CustomInterceptor();
                RequestApi requestApi = generator.CreateClassProxy<RequestApi>(interceptor);
                return await Task.FromResult(requestApi.Get<T>(httpClient, url, parameter));
            });
        }

        public static async Task<T> Post<T>(HttpClient httpClient, string url, object param) where T : class, new()
        {
            return await SoftInvoke(async () => 
            {
                ProxyGenerator generator = new ProxyGenerator();
                CustomInterceptor interceptor = new CustomInterceptor();
                RequestApi requestApi = generator.CreateClassProxy<RequestApi>(interceptor);
                return await Task.FromResult(requestApi.Post<T>(httpClient, url, param));
            });
        }

        /// <summary>
        /// 异常捕获拦截通用方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func"></param>
        /// <returns></returns>
        public static async Task<T> SoftInvoke<T>(Func<Task<T>> func) where T : class, new()
        {
            try
            {
                return await func();
            }
            catch (Exception exception)
            {
                LogHelper.LogManagerNlog.LogError(exception, $"SoftInvoke捕获到异常了 time: {DateTime.Now}");
                return new T();
            }
        }
    }
}
